package teaching.controller.baseInfoManage.classBaseInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import teaching.entity.Major;
import teaching.service.baseInfoManage.classBaseInfo.ClassBaseInfoService;
import teaching.service.baseInfoManage.common.BaseInfoCommonService;
import teaching.service.baseInfoManage.common.ExcelUtil;
import teaching.service.baseInfoManage.common.ExcelUtil.ExcelReader;



@Controller
@RequestMapping(value="classBaseInfo")
public class ClassBaseInfoController {
   
	 /**
	 * 班级信息service
	 */
	 @Autowired
	 private ClassBaseInfoService classBaseInfoService;
	 @Autowired
	 private BaseInfoCommonService baseInfoCommonService;
	 
	 /**
	  * 分页查询班级信息:共有四个条件Map(start+pageSize+majorName+enrollmentTime)
	  * 默认查询条件需设置(开始值start+pageSize);
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	 * @throws SQLException 
	  */
	 @RequestMapping(value="getClass")
	 @ResponseBody
	 public Map<String,Object> getClass(@RequestParam(value="page",required=false) Integer  page,@RequestParam(value="pageSize",required=false) Integer  pageSize,HttpServletResponse response,HttpServletRequest request) throws SQLException{
		
		 Map<String,Object> map2 = new HashMap<String, Object>();
		 List<Map<String,Object>> list = null;
		 int start = 0; 
		 if(page!=null&&pageSize!=null){
			 start = (page-1)*pageSize;
		 }
		 String majorName = request.getParameter("majorName");
		 String enrollmentTime = request.getParameter("enrollmentTime");
		 String classId = request.getParameter("classId");
		 String majorId = request.getParameter("majorId");
		// String collegeId = request.getParameter("collegeId");
		 Map<String,Object> map = new HashMap<String, Object>();
		 map.put("start", start);
		 map.put("pageSize", pageSize);
		 map.put("majorName", majorName);
		 map.put("classId", classId);
		 map.put("enrollmentTime2", enrollmentTime);
		 map.put("majorId2",majorId);
		    String id = request.getParameter("id");
		    String upId = request.getParameter("upId");	 
		    Map<String,Object> map3 = this.findId(id);
		    Iterator  i=map3.entrySet().iterator();
		    String str = "";
		    while(i.hasNext()){//只遍历一次,速度快
              Map.Entry  e=(Map.Entry)i.next();      
              str=(String) e.getKey();
		    }
		    switch (str) {
				case "collegeId":
					  map.put("collegeId", map3.get("collegeId"));
					  break;
				case "majorId":
					  map.put("majorId", map3.get("majorId"));
					  break;
			
				default:
					map.put("enrollmentTime", id);
					map.put("majorId", upId);
					break;
			}
		 try {
			 list = classBaseInfoService.getClass(map);
			 int countNum = classBaseInfoService.getClassCountNum(map);
			 map2.put("classList", list);
			 map2.put("countNum", countNum);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 return map2;
	 }	
	 
	 
	 /**
	  * 增加班级信息map(classId,classShortName,className,majorId,enrollmentTime,trainingSchemeId)
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	 * @throws ParseException 
	  */
	 @RequestMapping(value="addClass")
	 @ResponseBody
	 public Map<String,Object> addClass(HttpServletResponse response,HttpServletRequest request) throws ParseException{
		
		 Map<String,Object> map = new HashMap<String, Object>();
		 map.put("classId", request.getParameter("classId"));
		 map.put("classShortName", request.getParameter("classShortName"));
		 map.put("className", request.getParameter("className"));
		 map.put("majorId", request.getParameter("majorId"));
		 map.put("enrollmentTime", request.getParameter("enrollmentTime"));
		 map.put("trainingSchemeId", request.getParameter("trainingSchemeId"));
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		 map.put("createTime", sdf.parse(sdf.format(new Date())));
		 Map<String,Object> messageMap = new HashMap<String, Object>();
		 List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		 list.add(map);
		 try {
			int status = classBaseInfoService.addClass(list);
			if(status == 1){
				messageMap.put("message", "添加成功！");
			}else{
				messageMap.put("message", "添加失败！");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		 
		 return messageMap;
	 }
	 
	 /**
	  * 删除班级信息，级联删除学生和毕设结果
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	  */
	 @RequestMapping(value="deleteClass")
	 @ResponseBody
	 public Map<String,Object> deleteClass(HttpServletResponse response,HttpServletRequest request){
		
		 Map<String,Object> map = new HashMap<String, Object>();
		 String classId = request.getParameter("classId");
		 try {
			int status = classBaseInfoService.deleteClass(classId);
			if(status == 1){
				map.put("message", "删除成功！");
			}else{
				map.put("message", "删除失败！");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return map;
	 }
	 
	 /**
	  * 修改班级信息map(oldClassId,classId,className,majorId,enrollmentTime,trainingSchemeId)
	  * @author GuoFei
	  * @param response
	  * @param request
	  * @return
	  */
	 @RequestMapping(value="updateClass")
	 @ResponseBody
	 public Map<String,Object> updateClass(HttpServletResponse response,HttpServletRequest request){
		 
		 Map<String,Object> map = new HashMap<String, Object>();
		 String oldClassId = request.getParameter("oldClassId");
		 String classId = request.getParameter("classId");
		 if(oldClassId.endsWith(classId)&&oldClassId==classId){
			 map.put("oldClassId",oldClassId);
		 }else{
			 map.put("oldClassId", oldClassId); 
			 map.put("classId", classId);
		 }
				 	
		 map.put("className", request.getParameter("className"));
		 map.put("majorId", request.getParameter("majorId"));
		 map.put("enrollmentTime", request.getParameter("enrollmentTime"));
		 map.put("trainingSchemeId", request.getParameter("trainingSchemeId"));
		
		 Map<String,Object> resultMap = new HashMap<String, Object>();
		 
		 try {
			int status = classBaseInfoService.updateClass(map);
			if(status == 1){
				resultMap.put("message", "修改成功");
			}else{
				resultMap.put("message", "修改失败");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return resultMap;
	 }
	 /**
	  * 导出班级
	  * @param response
	  * @param request
	  * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws SQLException 
	  */
	 @RequestMapping(value="exportClass")
	 @ResponseBody
	 public Map<String,Object> exportClass(HttpServletRequest request) throws FileNotFoundException, IOException, SQLException{
		  
		    Map<String,Object> map = new HashMap<String, Object>(); 	    
			String basePath = this.getClass().getResource("/").getPath();
			if(System.getProperty("os.name").toLowerCase().indexOf("linux")>=0){
				basePath = basePath.substring(0, basePath.indexOf("/WEB-INF"));
			}else{
				basePath = basePath.substring(1, basePath.indexOf("/WEB-INF"));
			}
			
			String fileName = "template_class.xls";		
			String templatePath = basePath + "/template/baseInfoManage/" + fileName;
			// 先读取模板 
		    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templatePath));
		    HSSFWorkbook wb = new HSSFWorkbook(fs);  
		    //在webbook中添加一个sheet,对应Excel文件中的sheet  
		    HSSFSheet sheet = wb.getSheetAt(0);  
		    //在sheet中添加表头第0行 
		    HSSFRow row;
		    HSSFCellStyle cellStyle = ExcelUtil.setCellStyle(wb);
		    //写入实体数据 ,数据从数据库得到，  
		    List< Map<String,Object>> list = null;
		    Map<String,Object> map2 = new HashMap<String, Object>();
		    
		    //按条件查询
		    String majorId = request.getParameter("majorId");
		    String enrollmentTime = request.getParameter("enrollmentTime");
		    map2.put("majorId", majorId);
		    map2.put("enrollmentTime", enrollmentTime);
		    
		    //桉树查询
		    String id = request.getParameter("id");	   
		    Map<String,Object> map3 = this.findId(id);
		    Iterator  it=map3.entrySet().iterator();
		    String str = "";
		    while(it.hasNext()){//只遍历一次,速度快
              Map.Entry  e=(Map.Entry)it.next();      
              str=(String) e.getKey();
		    }
		    switch (str) {
				case "collegeId":
					  map2.put("collegeId", map3.get("collegeId"));
					  break;
				case "majorId":
					  map2.put("majorId2", map3.get("majorId"));
					  break;
			
				default:
					map2.put("enrollmentTime2", id);
					break;
			}
		    try {
				list = classBaseInfoService.getClass(map2);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    
		    if(list!=null){
		    	for (int i = 0; i < list.size(); i++) {
		    		 row = sheet.createRow( i + 1); 		    				                
		            row.createCell(0).setCellValue(list.get(i).get("classId").toString()); 
		            row.getCell(0).setCellStyle(cellStyle);
		            row.createCell(1).setCellValue(list.get(i).get("className").toString()); 
		            row.getCell(1).setCellStyle(cellStyle);
		            row.createCell(2).setCellValue(list.get(i).get("classShortName").toString());
		            row.getCell(2).setCellStyle(cellStyle);
		            row.createCell(3).setCellValue(list.get(i).get("majorName").toString()); 
		            row.getCell(3).setCellStyle(cellStyle);
		            row.createCell(4).setCellValue(list.get(i).get("enrollmentTime").toString()); 
		            row.getCell(4).setCellStyle(cellStyle);
		            row.createCell(5).setCellValue(list.get(i).get("trainingSchemeStore").toString()); 
		            row.getCell(5).setCellStyle(cellStyle);
		        
			                  		     	     
			    }  
		    }
		  
		    
	    try{  
	    	String path = "file/export";
	    	String realPath = request.getSession().getServletContext().getRealPath("/"+path);
	    	String pathtrue = realPath + "/"+fileName;
	        FileOutputStream fout = new FileOutputStream(pathtrue);  
	        wb.write(fout);  
	        fout.close();  
	        String uri =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
	       
	        map.put("message", uri+"/"+"TeachingMIS/"+path+"/"+fileName);
	    }  
	    catch (Exception e){ 
	    
	    	map.put("message", "导出失败！");
	        e.printStackTrace();  
	    }  
		 
		 return map;
	 }
	 
	 
		/**
		 * 导入班级
		 * @param fileName
		 * @return
		 * @throws SQLException 
		 * @throws ParseException 
		 */
		 @RequestMapping(value="importClass")
		 @ResponseBody
		 public Map<String,Object> importClass(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws SQLException, ParseException{
			    String fileName = file.getOriginalFilename();
				String saveFileName = UUID.randomUUID().toString().replaceAll("-", "") + "-" + fileName;
				String path = "file/import";
				String realPath = request.getSession().getServletContext().getRealPath("/"+path);
				String pathtrue = realPath + "/"+saveFileName;
				try {
					file.transferTo(new File(pathtrue));
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			
			 Map<String,Object> map = new HashMap<String, Object>();
			 ExcelUtil excelUtil = new ExcelUtil();
			 InputStream is = null;
			
			 try {
				is = new FileInputStream(pathtrue);
			 } catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			 }
			 ExcelReader excelReader = excelUtil.getExcelReader();
			 List<Map<Integer, String>>  list = excelReader.readExcelContent(is);	
			 List<Map<String,Object>>  list2 = new ArrayList<Map<String,Object>>();
			 if(list!=null){
				 for(int i = 0;i<list.size();i++){	
					 if(list.get(i).get(0) != null&&!"".equals(list.get(i).get(0))){
						 Map<String,Object> map2 = new HashMap<String, Object>();
						 map2.put("classId",list.get(i).get(0));
						 map2.put("className", list.get(i).get(1));
						 map2.put("classShortName", list.get(i).get(2));
						
						 map2.put("majorId",  baseInfoCommonService.getMajorIdByName(list.get(i).get(3)));
						 map2.put("enrollmentTime", list.get(i).get(4));
						 map2.put("trainingSchemeId",baseInfoCommonService.getTrainingSchemeIdByName(list.get(i).get(5)) );
						 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");						
						 map2.put("createTime", sdf.parse(sdf.format(new Date())));
						 list2.add(map2);					
					 }		 
				 }
			 }	
			
			 classBaseInfoService.addClass(list2); 
			 File file2 = new File(pathtrue);
			 if(file2.exists()){
				 file2.delete();
			 }
		     map.put("message", "导入成功！");
			
			 return map;
		 
		 }
		 
		  /**
		     * 查询树的时候判断ID是属于哪一学院，专业，班级
		     * @param id
		     * @return
		     * @throws SQLException
		     */
		    public  Map<String,Object>  findId(String id) throws SQLException{
		    	Map<String,Object> map = new  HashMap<String, Object>();
		    	List<Map<String,Object>> xyList = baseInfoCommonService.getXy();
		    	List<Map<String,Object>> majorList = baseInfoCommonService.getAllMajorAndId();
		    	List<Map<String,Object>> classList = baseInfoCommonService.getClassNameAndId();
		    	for(Map<String,Object> obj :xyList){
		    		if(obj.get("id").equals(id)){
		    			map.put("collegeId", id);
		    			return map;
		    		}
		    	}
		    	for(Map<String,Object> obj :majorList){
		    		if(obj.get("majorID").equals(id)){
		    			map.put("majorId", id);
		    			return map;
		    		}
		    	}
		    	for(Map<String,Object> obj :classList){
		    		if(obj.get("classId").equals(id)){
		    			map.put("classId", id);
		    			return map;
		    		}
		    	}
		    	return map;
		   
		    }
		
}
